package com.web3.management.security;

import com.web3.management.entity.Account;
import com.web3.management.repository.AccountRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;

/**
 * 客户端Token认证过滤器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AccountClientTokenFilter extends OncePerRequestFilter {

    private final AccountRepository accountRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = resolveToken(request);
        if (!StringUtils.hasText(token) || !AccountClientTokenUtils.isAccountClientToken(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        AccountClientTokenUtils.ParsedToken parsedToken = AccountClientTokenUtils.parseToken(token);
        if (parsedToken == null) {
            filterChain.doFilter(request, response);
            return;
        }

        Account account = accountRepository.findById(parsedToken.getAccountId()).orElse(null);
        if (account == null || !StringUtils.hasText(account.getClientTokenHash())) {
            filterChain.doFilter(request, response);
            return;
        }

        Date expiresAt = account.getClientTokenExpiresAt();
        if (expiresAt == null || expiresAt.before(new Date())) {
            log.debug("客户端Token已过期: accountId={} expiresAt={}", account.getId(), expiresAt);
            filterChain.doFilter(request, response);
            return;
        }

        String expectedHash = AccountClientTokenUtils.hashRawKey(parsedToken.getRawKey());
        if (!expectedHash.equals(account.getClientTokenHash())) {
            filterChain.doFilter(request, response);
            return;
        }

        AccountClientPrincipal principal = new AccountClientPrincipal(account.getId(), account.getName());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                principal,
                null,
                Collections.singleton(new SimpleGrantedAuthority("ROLE_ACCOUNT_CLIENT"))
        );
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return bearerToken;
    }
}
